package com.logicwin.aibala.action;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Message;

import com.logicwin.aibala.Aibala;
import com.logicwin.aibala.detailPackActivity.DetailDesc;
import com.logicwin.aibala.services.file.FileConnection;
import com.logicwin.aibala.ui.screens.screenmain.ScreenHome;
import com.logicwin.aibala.utils.MyLog;


public class DownloadSoftwareAction implements Runnable{
	private final String tag = "DownloadSoftwareAction";
	
	private String mSoftwareUrl = null;
	private int fileSize;
	private int step;
	private Thread downloadThread;
	
	private InputStream is = null;
    private FileOutputStream fos = null;
    
    private String downloadFile;
    private int mSoftId;
	
	private boolean isRun;
	private static HashMap<Integer,DownloadSoftwareAction> downloadMap = new HashMap<Integer,DownloadSoftwareAction>();
	
	public static boolean isEmpty(){
		return !downloadMap.isEmpty();
	}
	
	public DownloadSoftwareAction(int softId){
		mSoftId = softId;
	}
	
	public static DownloadSoftwareAction getInstance(int softId){
		if (downloadMap.containsKey(softId)){
			return downloadMap.get(softId);
		}
		else {
			DownloadSoftwareAction download = new DownloadSoftwareAction(softId);
			downloadMap.put(softId, download);
			return download;
		}
	}
	
	public boolean startAction(String url, int softId){
		isRun = true;
		step = 0;
		mSoftwareUrl = url;
		mSoftId = softId;
		downloadThread = new Thread(this);
		downloadThread.start();
		return true;
	}
	
	public void stop(){
		isRun = false;
		downloadCancel();
		downloadMap.remove(mSoftId);
	}

	@Override
	public void run() {
		try {
			downloadFile = FileConnection.getCurrentPath()
					+ "/software"
					+ mSoftwareUrl.substring(mSoftwareUrl.indexOf("sid=") + 4,
							mSoftwareUrl.length() - 1) + ".apk";
			FileConnection.deleteFile(downloadFile);
			downLoadFile(mSoftwareUrl, downloadFile);
			
			if (FileConnection.getFileSize(downloadFile)<fileSize)
				FileConnection.deleteFile(downloadFile);
			else {
				if (isRun) {
					FileConnection.chmodFile(downloadFile);
					openFile(new File(downloadFile));
				} else {
					FileConnection.deleteFile(downloadFile);
				}
			}
			downloadDone();
			downloadMap.remove(mSoftId);
		}
		catch (Exception ex){
			ex.printStackTrace();
		}
	}
	
	public void downLoadFile(String path, String fileName)
    {
        try
        {
            URL url = new URL(path);
            HttpURLConnection urlcon=(HttpURLConnection)url.openConnection();   
            //根据响应获取文件大小 
            fileSize=urlcon.getContentLength(); 
            downloadTotal();
        	downloadStep(step);
            step++;
            
            is = url.openStream();
            File file = new File(fileName);

            fos = new FileOutputStream(file, false);
            
            download(is, fos);

        } catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }

    public void download(InputStream is, FileOutputStream fos)
    {
        try
        {
        	long sendTime = System.currentTimeMillis();
            byte[] buff = new byte[256];
            int count = 0;
            int hasRead = 0;
            while (isRun)
            {
                hasRead = is.read(buff);
                count += hasRead;
                if (hasRead < 0)
                {
                    break;
                }
                fos.write(buff, 0, hasRead);
                if (count>fileSize*step/50){
//                	downloadStep(step);
                	step++;
                }
                if (System.currentTimeMillis()-sendTime>1000){
                	downloadStep(step);
                	sendTime = System.currentTimeMillis();
                }
            }
        } catch (Exception ex)
        {
            ex.printStackTrace();
        } finally
        {
            try
            {
                if (is != null)
                {
                    is.close();
                }
                if (fos != null)
                {
                    fos.close();
                }
            } catch (Exception ex)
            {
                ex.printStackTrace();
            }
        }
    }
	
	private void openFile(File f)
    {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(android.content.Intent.ACTION_VIEW);
        String type = getMIMEType(f);
        intent.setDataAndType(Uri.fromFile(f), type);
        Aibala.getCurrentContext().startActivity(intent);
    }
	
	private String getMIMEType(File f)
    {
        String type = "";
        String fName = f.getName();
        String end = fName
                .substring(fName.lastIndexOf(".") + 1, fName.length())
                .toLowerCase();
        if (end.equals("m4a") || end.equals("mp3") || end.equals("mid")
                || end.equals("xmf") || end.equals("ogg") || end.equals("wav"))
        {
            type = "audio";
        } else if (end.equals("3gp") || end.equals("mp4"))
        {
            type = "video";
        } else if (end.equals("jpg") || end.equals("gif") || end.equals("png")
                || end.equals("jpeg") || end.equals("bmp"))
        {
            type = "image";
        } else if (end.equals("apk"))
        {
            type = "application/vnd.android.package-archive";
        } else
        {
            type = "*";
        }
        if (end.equals("apk"))
        {
        } else
        {
            type += "/*";
        }
        return type;
    }
	

	public void downloadStep(int step) {
		
		Message message = Message.obtain();
		MyLog.info(tag, "downloadStep message="+message+"   "+Aibala.getCurrentContext());
        message.obj = "downloading/"+step+"/"+mSoftId;
        if (Aibala.getCurrentContext() instanceof DetailDesc)
        	DetailDesc.messageHandler.sendMessage(message);
        if (Aibala.getCurrentContext() instanceof ScreenHome)
        	ScreenHome.messageHandler.sendMessage(message);
	}


	public void downloadDone() {
		
		Message message = Message.obtain();
		MyLog.info(tag, "downloadDone message="+message+"   "+Aibala.getCurrentContext());
        message.obj = "endDownload"+"/"+mSoftId;
        if (Aibala.getCurrentContext() instanceof DetailDesc)
        	DetailDesc.messageHandler.sendMessage(message);
        if (Aibala.getCurrentContext() instanceof ScreenHome)
        	ScreenHome.messageHandler.sendMessage(message);
	}


	public void downloadTotal() {
		
		Message message = Message.obtain();
		MyLog.info(tag, "downloadTotal message="+message+"   "+Aibala.getCurrentContext());
        message.obj = "startDownload"+"/"+mSoftId;
        if (Aibala.getCurrentContext() instanceof DetailDesc)
        	DetailDesc.messageHandler.sendMessage(message);
        if (Aibala.getCurrentContext() instanceof ScreenHome)
        	ScreenHome.messageHandler.sendMessage(message);
	}


	public void downloadCancel() {
		
		Message message = Message.obtain();
		MyLog.info(tag, "downloadCancel message="+message+"   "+Aibala.getCurrentContext());
        message.obj = "cancelDownload"+"/"+mSoftId;
        if (Aibala.getCurrentContext() instanceof DetailDesc)
        	DetailDesc.messageHandler.sendMessage(message);
        if (Aibala.getCurrentContext() instanceof ScreenHome)
        	ScreenHome.messageHandler.sendMessage(message);
	}
	
}
